<template>
	<view v-if="blog.length!=0" class="all">
		<login-dialog ref="login" @afterLogin="afterLogin"></login-dialog>
		<view class="blog">
			<p class="text">
				<view class="">
					<image :src="host+blog.user.avatar" mode="" class="image-avatar"></image>
				</view>
				<view style="width: 100%;">
					<p class="title">{{blog.title}}
						<image v-if="!like_ids.includes(blogId)" style="float: right;width: 50rpx;height: 50rpx;"
							src="../../static/icons/ic_tag.png" @click="changeLike(true)"></image>
						<image v-else style="float: right;width: 50rpx;height: 50rpx;"
							src="../../static/icons/ic_tag_fill.png" @click="changeLike(false)"></image>
					</p>
					<text class="userAndTime">{{blog.user.nickName}}@{{blog.createTime}}</text>
				</view>
			</p>
			<view class="blog_content">
				<p v-html="blog.content"></p>
				<img class="image-picture" :src="host+blog.picture" mode=""></img>
			</view>
			<view class="item-icon">
				<img v-if="!good_ids.includes(blog.id)" src="/static/icons/ic_good.png" @click="onGood(blog.id)" alt="">
				<img v-else src="/static/icons/ic_good_fill.png" @click="deleteGood(blog.id)" alt="">
				<!--显示点赞数-->
				<span v-if="blog.good!=0" class="item-desc">{{blog.good}}</span>
				<img src="/static/icons/ic_comment.png" alt="">
				<!--显示评论数-->
				<span v-if="blog.comments.length!=0" class="item-desc">{{blog.comments.length}}</span>
				<img src="/static/icons/ic_count.png" alt="">
				<!--显示阅读数-->
				<span v-if="blog.readCount!=0" class="item-desc">{{blog.readCount}}</span>
			</view>
		</view>
		<view class="blog_comment" v-for="(parentcomment,parentindex) in parentComments" :key="parentcomment.id"  @longpress="deleteComment(parentcomment,parentindex,0,true)">
			<view class="comment_head">
				<view class="comment_avatar">
					<image :src="host+parentcomment.avatar" mode=""></image>
				</view>
				<view class="">
					<p style="color: skyblue;font-size: 15px;">
						<text @click="clickToReply(parentcomment)">{{parentcomment.nickName}}</text>
<!-- 						<text class="deleteComment" @click="deleteComment(parentcomment.id,parentindex,0,true)"
							v-if="parentcomment.owner">删除</text> -->
					</p>
					<p style="color: #999;font-size: 12px;">{{parentcomment.createTime}}</p>
				</view>
			</view>
			<view class="commet_content">
				<text>{{parentcomment.content}}</text>
			</view>
			<view class="replieComments" v-for="(replieComment,replieIndex) in replieComments[parentindex]"
				:key="replieComment.id" @longpress="deleteComment(replieComment,parentindex,replieIndex,false)">
				<text style="font-size: 12px;color: skyblue;"
					@click="clickToReply(replieComment)">{{replieComment.nickName}}</text>
				<text style="font-size: 12px;color: orange;">@{{replieComment.toUser}}</text>
				<text style="font-size: 12px;color: #999;">{{replieComment.createTime}}</text>
				<!-- <text class="deleteComment" @click="deleteComment(replieComment.id,parentindex,replieIndex,false)"
					v-if="replieComment.owner">删除</text> -->
				<p>{{replieComment.content}}</p>
			</view>
		</view>
		<view class="input_comment">
			<image :src="avatar" mode="aspectFill" class="input_comment_avatar" @click="Tologin()"></image>
			<textarea auto-height="" value="" :placeholder="CommentTo" v-model="postCommentParame.content" />
			<image src="../../static/icons/commit.png" mode="" class="input_comment_action" @click="postComment">
			</image>
		</view>
	</view>
</template>

<script>
	let like_ids = "like_ids";
	let toUser = "";
	export default {
		data() {
			return {
				blogId: "",
				blog: [],
				host: this.$params.host,
				good_ids: [],
				like_ids: [],
				parentComments: [],
				replieComments: [],
				CommentTo: "请输入评论内容",
				userInfo: [],
				avatar: "",
				postCommentParame: {
					nick_name: "",
					avatar: "",
					email: "",
					content: "",
					blog_id: "",
					parent_id: null,
					token: "",
					is_owner: false
				}
			}
		},
		onLoad(options) {
			let user = uni.getStorageSync(this.$params.userInfo);
			this.avatar = getApp().globalData.userInfo.avatar;
			if (user) {
				this.userInfo = user;
				this.postCommentParame.nick_name = user.nickName;
				this.postCommentParame.avatar = user.avatar;
				this.postCommentParame.email = user.email;
				this.postCommentParame.token = user.token;
				this.postCommentParame.blog_id = options.id;
				this.avatar = user.avatar;
			}
			if (uni.getStorageSync(like_ids)) {
				this.like_ids = uni.getStorageSync(like_ids);
			}
			this.blogId = options.id;
			this.getBlog(options.id);
			this.addReadCount(options.id);
			let good_ids = uni.getStorageSync(this.$params.cache_good_ids);
			if (good_ids) {
				this.good_ids = good_ids;
			}
		},
		methods: {
			getBlog(id) {
				this.$request.get("/api/v1/blogs/" + id, res => {
					this.blog = res.data;
					this.blog.createTime = this.$util.formatTime(new Date(this.blog.createTime));
					this.blog.content = res.data.content.replace(/\<img/gi,
						'<img style ="display: block;margin: auto;width: 90%;height: 500rpx;border-radius: 8rpx;"'
					);
					this.blog.comments.forEach(comment => {
						comment.createTime = this.$util.formatTime(new Date(comment.createTime));
					})
					this.formatComments(this.blog.comments);
					uni.setNavigationBarTitle({
						title: this.blog.user.nickName
					});
				}, () => {})
			},
			formatComments(comments) {
				if (comments.length == 0) {
					return;
				}
				let rootComments = [];
				comments.forEach(c => {
					if (c.parentId == null) {
						rootComments.push(c);
					}
					if (c.email === this.userInfo.email) {
						c.owner = true;
					}
				})
				rootComments.sort((a, b) => {
					return new Date(b.createTime) - new Date(a.createTime)
				});
				let replies = new Array(rootComments.length).fill([]);
				let index = 0;
				rootComments.forEach(r => {
					let cmmts = [];
					cmmts = cmmts.concat(this.getChildren(r, comments));
					replies[index++] = cmmts;
					comments = comments.filter(c => cmmts.every(cc => cc.id != c.id));
				})
				this.parentComments = rootComments;
				this.replieComments = replies;
				console.log(this.parentComments);
				console.log(this.replieComments);
			},
			getChildren(parentComment, comments) {
				let childComments = [];
				comments.forEach(comment => {
					if (comment.parentId == parentComment.id) {
						comment.toUser = parentComment.nickName;
						childComments.push(comment);
						childComments = childComments.concat(this.getChildren(comment, comments));
					}
				});
				return childComments;
			},

			// addReadCount(id){
			// 	let pages = getCurrentPages()
			// 	let prev = pages[pages.length-2]
			// 	this.$request.postParam(this.host+"api/v1/blogs/read","id="+id,res=>{
			// 		if(prev!=null){
			// 			prev.addReadCount(id,res.data);
			// 		}
			// 		this.blog.readCount = res.data;
			// 	},()=>{});
			// },
			addReadCount(id) {
				this.$request.postParam("api/v1/blogs/read", "id=" + id, res => {
					this.blog.readCount = res.data;
					this.$noti.post(this.$params.noti_refresh_count, {
						id: id,
						count: res.data,
					});
				}, () => {});
			},
			onGood(id) {
				this.$request.postParam(this.$params.onGood_url, "id=" + id, res => {
					this.blog.good = res.data;
					this.good_ids.push(id);
					uni.setStorageSync(this.$params.cache_good_ids, this.good_ids);
					this.$noti.post(this.$params.noti_good_action, {
						id: id,
						goodCount: res.data,
						isGood: true
					});
				}, () => {});

			},
			deleteGood(id) {
				this.$request.postParam(this.$params.deleteGood_url, "id=" + id, res => {
					this.blog.good = res.data;
					this.$util.remove(this.good_ids, this.good_ids.indexOf(id));
					uni.setStorageSync(this.$params.cache_good_ids, this.good_ids);
					this.$noti.post(this.$params.noti_good_action, {
						id: id,
						goodCount: res.data,
						isGood: false
					});
				}, () => {});
			},
			changeLike(isLike) {
				if (isLike) {
					this.like_ids.push(this.blogId);
					uni.setStorageSync(like_ids, this.like_ids);
					uni.showToast({
						title: "收藏成功",
						icon: 'success',
						mask: false,
						duration: 500
					});
				} else {
					this.$util.removeByValue(this.like_ids, this.blogId);
					uni.setStorageSync(like_ids, this.like_ids);
					uni.showToast({
						title: "取消收藏成功",
						icon: 'success',
						mask: false,
						duration: 500
					});
				}
			},
			clickToReply(item) {
				if (item.id == this.postCommentParame.parent_id) {
					this.CommentTo = "请输入评论内容";
					this.postCommentParame.parent_id = null;
					toUser = "";
				} else {
					this.CommentTo = item.nickName;
					this.postCommentParame.parent_id = item.id;
					toUser = item.nickName;
				}
			},
			Tologin() {
				if (this.userInfo.length == 0) {
					this.$refs.login.$refs.shell.show();
				} else {
					uni.showModal({
						title: "退出登录",
						content: "确认退出登录？",
						success: res => {
							if (res.confirm) {
								this.$request.postParam("api/v1/logout", "token=" + uni.getStorageSync(
									"userInfo").token, res => {}, () => {})
								localStorage.removeItem("userInfo");
								this.userInfo = [];
								getApp().globalData.userInfo = {
									avatar: "/static/icons/default_user.png",
									email: "",
									id: "",
									nickName: "",
									token: "",
									type: -1,
									userName: "",
								};
								this.avatar = "/static/icons/default_user.png"
							}
						}
					})
				}
			},
			postComment() {
				if(!uni.getStorageSync(this.$params.userInfo)){
					uni.showToast({
						icon:'error',
						title:"请先登录!",
					})
					return;
				};
					this.$request.post("api/v1/blogs/comment", this.postCommentParame, res => {
						if (!res.success) {
							return;
						}
						res.data.owner = true;
						res.data.toUser = toUser;
						res.data.createTime = this.$util.formatTime(new Date(res.data.createTime));
						if (this.postCommentParame.parent_id == null) {
							this.parentComments.unshift(res.data);
							this.replieComments.unshift(new Array);
						} else {
							l1: for (let i = 0; i < this.parentComments.length; i++) {
								if (this.parentComments[i].id == this.postCommentParame.parent_id) {
									this.replieComments[i].push(res.data);
									break;
								}
								for (let j = 0; j < this.replieComments[i].length; j++) {
									if (this.postCommentParame.parent_id == this.replieComments[i][j].id) {
										this.replieComments[i].push(res.data);
										break l1;
									}
								}
							}
						}
						this.postCommentParame.content = "";
						this.postCommentParame.parent_id = null;
						this.CommentTo = "请输入评论内容";
						uni.showToast({
							icon: 'success',
							title: "发表成功",
							duration: 1500
						})
					}, () => {});
			},
			deleteComment(Comment, parentindex, replieIndex, isparent) {
				if(this.userInfo.email===Comment.email){
					uni.showModal({
						title:"确定？",
						content:"是否删除评论？",
						success:res=>{
							if(res.confirm){
								this.$request.deleteParam("api/v1/blogs/comments/delete/" + Comment.id, "token=" + this.userInfo.token, res => {
									console.log(res);
									if(res.success){
										if (isparent) {
											this.parentComments.splice(parentindex, 1);
											this.replieComments.splice(parentindex, 1);
										} else {
											this.replieComments[parentindex].splice(replieIndex, 1);
										}
										uni.showToast({
											icon: 'success',
											title: res.message,
											duration: 1500
										})
									}else{
										uni.showToast({
											icon: 'error',
											title: res.message,
											duration: 1500
										})
									}
								}, () => {});
							}
						}
					})
				}
			},
			afterLogin() {
				this.userInfo = getApp().globalData.userInfo;
				this.avatar = getApp().globalData.userInfo.avatar;
			}
		}
	}
</script>
<style>
	@import url("detail.css");
</style>